package cn.wolfcode.wolf2w.redis.impl;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.redis.IStrategyRedisService;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class StrategyRedisServiceImpl implements IStrategyRedisService {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IStrategyService strategyService;

    @Override
    public List<StrategyStatisVO> getStrategyStatisVos() {


        Set<String> keys = redisTemplate.keys(RedisKeys.STRATEGY_STATIS.join("*"));

        ArrayList<StrategyStatisVO> list = new ArrayList<>();
        for (String key : keys) {
            String voStr = redisTemplate.opsForValue().get(key);
            list.add(JSON.parseObject(voStr,StrategyStatisVO.class));
        }
        return list;
    }

    @Override
    public StrategyStatisVO getStatisVo(String id) {
        // 准备一个空的统计VO对象
        StrategyStatisVO strategyStatisVO = new StrategyStatisVO();
        // 拿到当前攻略的id 凭借成redis中的key
        String key = RedisKeys.STRATEGY_STATIS.join(id);
        // 判断key是否存在redis缓存中
        if (!redisTemplate.hasKey(key)) {
            // 若不存在,则初始化VO对象
            Strategy strategy = strategyService.get(id);
            BeanUtils.copyProperties(strategy,strategyStatisVO);
        }else { // 若存在则直接获取vo对象
            String voStr = redisTemplate.opsForValue().get(key);
            strategyStatisVO = JSON.parseObject(voStr,StrategyStatisVO.class);
        }
        return strategyStatisVO;
    }

    @Override
    public void setStatisVo(String sid, StrategyStatisVO vo) {
        String key = RedisKeys.STRATEGY_STATIS.join(sid);
        redisTemplate.opsForValue().set(key, JSON.toJSONString(vo));
    }

    @Override
    public boolean isExist(String id) {

        return redisTemplate.hasKey(RedisKeys.STRATEGY_STATIS.join(id));
    }
}
